export default class screenCapApi{
	private static exportIndex=0;
	private static _currentRecorder=null;
	private static recordedChunks = [];
	static init() {
	    screenCapApi.startRecord();
	}
	
	public static startRecord() {
		navigator.mediaDevices.getUserMedia({
			audio: {
				mandatory: {
					chromeMediaSource: 'desktop'
				}
			},
			video: {
				mandatory: {
					chromeMediaSource: 'screen',
					minWidth: window.screen.width,
					maxWidth: window.screen.width,
					minHeight: window.screen.height,
					maxHeight: window.screen.height
				}
			}
		}).then(stream => {
			let systemAudioTrack = stream.getAudioTracks()[0]; //系统音轨
			let systemVideoTrack = stream.getVideoTracks()[0];
			navigator.mediaDevices.getUserMedia({
				audio: true,
				video: false
			}).then(audioStream => { //获取麦克风音频【流】
				let audioContext = new AudioContext(); //创建音频上下文
				let microphoneStreamNode = audioContext.createMediaStreamSource(audioStream); //创建节点
				let sysAudioStream = new MediaStream(); //创建一个媒体流
				sysAudioStream.addTrack(systemAudioTrack); //把系统音轨添加到新的媒体流
				let sysAudioStreamNode = audioContext.createMediaStreamSource(sysAudioStream); //创建系统音频节点
				let mixedOutput = audioContext.createMediaStreamDestination(); //创建一个输出媒体流节点
				microphoneStreamNode.connect(mixedOutput); //把麦克风节点和系统音节点添加到输出媒体流
				sysAudioStreamNode.connect(mixedOutput); //把麦克风节点和系统音节点添加到输出媒体流
				var _currentStream = mixedOutput.stream;
				_currentStream.addTrack(systemVideoTrack);

				this._currentRecorder = new MediaRecorder(_currentStream, {
					mimeType: "video/mp4;codecs=vp9",
					audioBitsPerSecond: 2000000,
					videoBitsPerSecond: 2000000
				});
				this._currentRecorder.ondataavailable = e => {
					this.recordedChunks.push(e.data);
				};
				this._currentRecorder.start(20);
			}).catch(err => {
				console.log(err)
			});
		
		}).catch(error => {
			alert("设备初始化失败...");
			console.error(error)
		});
	}
	
	private static stopRecord() {
	  const url = URL.createObjectURL(new Blob(this.recordedChunks, {'type':'video/mp4'}));
	  const a = document.createElement('a');
	  var recordname= this.timeFormat(new Date())+".mp4";
	  a.download =recordname;
	  a.href = url;
	  document.body.appendChild(a);
	  a.click();
	  a.remove();
	}
	
	private static done() {
		this._currentRecorder.stop();
		this._currentRecorder.onstop = () => {
			console.log(this.recordedChunks)
			this.recordedChunks=[]
		};
	}
	
	private static timeFormat(time){//获取当前时间
		let year = time.getFullYear();
		let month = time.getMonth() + 1;
		this.exportIndex++
		if (month < 10) {
				month = "0" + month;
		}
		let day = time.getDate();
		return "wxtv" + year + month + day+"0"+Math.floor(Math.random() * 10)+this.exportIndex;
	}
}